package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService{
    @Autowired
    private MongoTemplate template;

    @Autowired
    private TravelRepository travelRepository;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Travel travel) {
        travel.setId(null);
        travelRepository.save(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public void update(Travel travel) {

        travelRepository.save(travel);
    }

    @Override
    public Travel get(String id) {
        // 查询数据里对应的游记
        Travel travel = travelRepository.findById(id).get();
        // 如果有查询到游记信息
        if (travel != null){
            // 维护对象数据, 根据页面传过来的游记id, 同时对用户信息和目的地进行更新
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }
        return travel;
    }

    @Override
    public List<Travel> list() {
        return travelRepository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();

        long totalCount = template.count(query, Travel.class);

        if (totalCount == 0){
            return Page.empty();
        }

        // 根据不同的审核状态进行查询
        query.addCriteria(Criteria.where("state").is(qo.getState()));

        // 根据出行时间进行查询
        TravelCondition day = qo.getDay();
        if (day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }

        // 根据人均消费进行查询
        TravelCondition perExpend = qo.getMoney();
        if (perExpend != null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpend.getMin()).lte(perExpend.getMax()));
        }

        // 根据目的地查询
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        Pageable pageable = null;
        // 按最新发布排序
        if (qo.getOrderType() == 1){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
            query.with(pageable);
        }
        // 按最火进行排序
        if (qo.getOrderType() == 2){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "viewnum");
            query.with(pageable);
        }
        // 按id进行排序
        if (qo.getOrderType() == -1){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
            query.with(pageable);
        }

        List<Travel> travels = template.find(query, Travel.class);

        // 维护对象数据, 根据页面传过来的游记id, 同时对用户信息进行更新
        for (Travel travel : travels){
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }

        return new PageImpl<>(travels,pageable,totalCount);

    }

    @Override
    public void changeAudit(String id, int state) {
        Travel travel = this.get(id);
        // 判断是否满足条件
        // 判断游记是否存在
        if (!StringUtils.hasLength(travel.getId())){
            throw new LogicException("发布的游记不存在");
        }
        // 判断游记的状态是否为待审核状态
        if ((state == Travel.STATE_WAITING)){
            throw  new LogicException("游记不是待审核状态");
        }

        // 如果审核通过
        if (state == Travel.STATE_RELEASE){
            //1.修改状态为审核通过状态
            travel.setState(state);
            //2.修改发布时间
            travel.setReleaseTime(new Date());
            //3.最后更新时间(new Date())
            travel.setLastUpdateTime(new Date());
            // 进行update更新操作
            this.update(travel);
        }
        // 如果审核不通过
        if (state == Travel.STATE_REJECT){
            //1.修改状态为审核不通过状态
            travel.setState(state);
            // 修改发布时间
            travel.setReleaseTime(null);
            // 修改更新时间
            travel.setLastUpdateTime(new Date());
            // 进行update更新操作
            this.update(travel);
        }else {
            throw new RuntimeException("状态不允许修改");
        }
    }

    @Override
    public void saveOrUpdate(Travel travel, UserInfo userInfo) {

        travel.setUserId(userInfo.getId());

        // 获取目的地名称
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());

        // 更新时间
        travel.setLastUpdateTime(new Date());

        if (StringUtils.hasLength(travel.getId())){
            this.update(travel);
        }else {
            this.save(travel);
            // 创建时间
            travel.setCreateTime(new Date());
        }
    }


    @Override
    public List<Travel> queryByDestName(String keyword) {
        // 通过目的地查询相关游记
        List<Travel> travels = travelRepository.findByDestName(keyword);

        for (Travel travel : travels) {
            // 维护对象数据,同时对用户信息和目的地进行更新
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }
        return travels;
    }
}
